# author: wanyancan
# date: 2007-06-20
# copy is righted @ gmail.com

import math, random

# dummy function
latfn = lambda x:math.log(math.tan(x/180.0*math.pi)+1.0/math.cos(x/180.0*math.pi))
dtr = lambda x:x/180.0*math.pi

# some constant
latC = latfn(85.0511)

def dtb(dig, lv):  # 0.567 to 0.10010
    """convert a [0,1] to 101010101010 string """
    rt = ""
    lv = int(lv)
    for i in range(lv):
        dg, dig = int(dig*2), dig*2.0-int(dig*2)
        rt += str(dg)
    return rt

def LongDegS(long):
    """generate longitude percentage [0,1]"""
    long = long*1.0
    long = long%360.0
    if long >180.0:
        long -= 360.0
    pos = long/360.0+0.5
    return pos

def LatDegS(lat):
    """generate latitude percentage [0,1]"""
    lat = lat*1.0
    lat = lat%180.0
    if lat > 90.0:
        lat -= 180.0
    pos = latfn(lat)/latC/2.0+0.5
    return pos

def khStr(blat,blon, lv):
    """from two binary string (lat,lon) generate t-string """
    la,lg = dtb(blat,lv),dtb(blon,lv)
    rt = ""
    for i in range(lv):
        if la[i]=='1' and lg[i]=='1':
            rt+='r'
        elif la[i]=='1' and lg[i]=='0':
            rt+='q'
        elif la[i]=='0' and lg[i]=='1':
            rt+='s'
        elif la[i]=='0' and lg[i]=='0':
            rt+='t'
        else:
            rt+='-'
    return 't'+rt

def genRange(lat,lon, lv, r):
    """return (Lat_range, Lon_range) in percentage"""
    lat = LatDegS(lat)
    lon = LongDegS(lon)
    det = 1.0
    for i in range(lv):
        det /= 2.0
    x = []
    y = []
    for i in range(-r,r):
        if lon+i*det>=0.0 and lon+i*det<=1.0:
            x.append(lon+i*det)
        if lat+i*det>=0.0 and lat+i*det<=1.0:
            y.append(lat+i*det)
    return (y,x)

def genJobs(lat,lon, lv, r):
    """return: array[y][x] of t-string position.
    lower-left corner is x=0,y=0
    x-axis points to the right
    y-axis points to the top"""
    ll = genRange(lat,lon,lv,r)
    sz = len(ll[0])
    rt = []
    oldstr = ""
    for x in range(sz):
        rt.append([])
        for y in range(sz):
            if oldstr != khStr(ll[0][x], ll[1][y],lv):
                oldstr = khStr(ll[0][x], ll[1][y],lv)
                rt[x].append(oldstr)
    rt.reverse()
    return rt

# given a position:(lat,lon), zoom level:lv, range radius:r
# return jobs list
job =  genJobs( lat=28.858222473, lon=121.125671588,lv=14,r=6)  # linhai
#job =  genJobs( lat=39.963676374, lon=116.315271896,lv=17,r=5)  # tian'an men  300*300
#job = genJobs(-37.791862,144.960432,lv=17,r=3)
## demo
## write to mymap.html
out = open('mymap.html','w')
##for y in range(len(job)):
##    for x in range(len(job[y])):
##        out.write('<img class="map" alt="%s.jpg" src="http://%s.google.com/kh?n=404&v=18&t=%s">'%(job[y][x],random.choice(['kh0','kh1','kh2','kh3']),job[y][x]))
##    out.write('<br>\n')
out.write('''<style type="text/css">
img{width:256}
</style>
''')
out.write('<div><table table-layout="auto" cellpadding="0" cellspacing="0">\n')
out.write('<COLGROUP span="%s" width="0*"></COLGROUP>'%len(job))
for y in range(len(job)):
    out.write('<tr>')
    for x in range(len(job[y])):
        out.write('<td><img class="map" alt="%s.jpg" src="http://%s.google.com/kh?n=404&v=18&t=%s"></td>'%(job[y][x],random.choice(['kh0','kh1','kh2','kh3']),job[y][x]))
    out.write('</tr>\n')
out.write('</table></div>')
out.close()
